<template>
	<div>
		<div class="questionnaire-h5">
		    <div class="qs-box content">
		    	<div class="qs-dev">
		    		<span>项目名称：&nbsp;{{project.name}}</span>
		    	</div>
		    	<div class="qs-dev">
		    		<span>客户姓名：</span>
		        	<input type="text" id="name" v-model="customer.customerName" style="width:70%;height:30px;" class="qs-input" placeholder="请输入您的姓名">
		    	</div>
		    	<div class="qs-dev">
		    		<span>联系电话：</span>
		        	<input type="text" id="phone" v-model="customer.customerPhone" style="width:70%;height:30px;" class="qs-input" placeholder="请输入您的手机号">
		    	</div>
		    	<div>
		    		<span style="color:red">*请填写《购房合同》上其中一个购房人的姓名、联系电话</span>
		    	</div>
		    	<br />
		    	<h2 align="center">{{title}}</h2>
		    	<br />
		        <div class="qs-list font14" v-for="(info,index) in questionList" v-bind:questionId="info.id" v-bind:level="info.level" v-bind:answerType="info.answerType" v-bind:isRequired="info.isRequired">
		        	<h4 style="font-size: 18px; font-weight: blod;" v-bind:id="'h4_'+info.id">
		        		{{info.problemCode}}&nbsp;{{info.question}}
		        		<span v-if="info.answerType == '1'">（单选）</span>
		        		<span v-else-if="info.answerType == '2'">（多选）</span>
		        	</h4>
		        	<p class="qs-note font14 color999" v-show="info.questionnaireDescribe != ''">{{info.questionnaireDescribe}}</p>
		        	<div class="flex-list" v-if="info.answerType == '1'">
		        		<label v-for="ar in JSON.parse(info.arrayJson)">
		        			<span class="radio-default radio-single" @click="radioCheck">
		        				<input type="radio" class="radioclass" v-if="ar.answer != 'select_other'" v-bind:value="ar.id" v-bind:name="'radioAnswer_'+info.id">
		        				<input type="radio" class="radioclass" v-else v-bind:value="ar.id" at="select_other" v-bind:name="'radioAnswer_'+info.id" >
		        			</span>
		        			<span class="radio-txt" v-if="ar.answer != 'select_other'">{{ar.answer}}</span>
		        			<span class="radio-txt" v-else>其他</span>
		        		</label>
		        		<div class="more-input" style="width:100%" v-if="info.answer.indexOf('select_other') > 0">
	        				<input type="text" class="qs-input" v-bind:id="'input_'+info.id" style="height:30px;" placeholder="请输入相关信息">
	        			</div>
		        	</div>
		        	<div class="flex-list" v-else-if="info.answerType == '2'">
		        		<label v-for="ar in JSON.parse(info.arrayJson)">
		        			<span class="radio-default radio-multiple" @click="checkboxCheck">
		        				<input type="checkbox" class="radioclass" v-if="ar.answer != 'select_other'" v-bind:value="ar.id" v-bind:name="'checkAnswer_'+info.id">
		        				<input type="checkbox" class="radioclass" v-else at="select_other" v-bind:value="ar.id" v-bind:name="'checkAnswer_'+info.id">
		        			</span>
		        			<span class="radio-txt" v-if="ar.answer != 'select_other'">{{ar.answer}}</span>
		        			<span class="radio-txt" v-else>其他</span>
		        		</label>
		        		<div class="more-input" style="width:100%" v-if="info.answer.indexOf('select_other') > 0">
	        				<input type="text" class="qs-input" v-bind:id="'input_'+info.id" style="height:30px;" placeholder="请输入相关信息">
	        			</div>
		        	</div>
		        	<div class="flex-list" v-else-if="info.answerType == '3'">
		        		<input type="text" class="qs-input" v-bind:id="'input_'+info.id" style="height:30px;" placeholder="请输入相关信息">
		        	</div>
		        </div>
		    </div>
		    <div style="height:50px;">&nbsp;</div>
		</div>
		<div style="width:50%;" v-show="showBtn">
			<a class="btn-default btn-save orange-bg" style="width:50%;" @click="resetAnswer">重置</a>
		</div>
		<div style="width:50%; float:right;" v-show="showBtn">
			<a class="btn-default btn-save orange-bg" style="width:50%;" @click="saveAnswer">保存</a>
		</div>
	</div>
</template>

<script>
	export default{
		data(){
			return{
				customer: {
					customerName: '',
					customerPhone: '',
					agentId:''
				},
				title: '',
				project: {
					id: '',
					name: ''
				},
				userList: [],
				questionList: [],
				answerList: [],
				showBtn: true
			}
		},mounted:function(){
			this.initQuestionnaire();
			this.initQuestion();
		},methods:{
			//初始化问卷题目及项目名称
			initQuestionnaire(){
				var _self = this;
				var params = {
					"questionnaireId": _self.$route.params.id
				};
				var url = _self.utilHelper.apiUrl + "/customer/projectQuestion/questionnaireTitle";
				_self.$http.post(url, params).then((response)=>{
					var body = response.body;
					if(body.res == "1"){
						_self.title = body.obj.title;
						_self.project.id = body.obj.projectId;
						_self.project.name = body.obj.projectName;
						_self.userList = body.obj.userList;
					}
				});
			},
			//初始化题目及答案
			initQuestion(){
				var _self = this;
				var params = {
					"questionnaireId": _self.$route.params.id
				};
				var index = layer.load(0, {shade: false});
				var url = _self.utilHelper.apiUrl + "/customer/projectQuestion/questionList";
				_self.$http.post(url, params).then((response)=>{
					layer.close(index);
					var body = response.body;
					if(body.res == "1"){
						_self.questionList = body.obj.entity;
					}
				});
			},
			//单选框选中事件
			radioCheck(event){
				var parent = $(event.target).parent();
				parent.parent().parent().find('.radio-single').removeClass("on");
			    parent.parent().parent().find('input.radioclass').removeAttr("checked");
			    parent.addClass("on").find('input.radioclass').attr("checked", true);
			},
			//复选框选中事件
			checkboxCheck(event){
				var parent = $(event.target).parent();
				if( parent.hasClass("on") ) {
        	        parent.removeClass("on").find('input.radioclass').removeAttr("checked");
        	    } else {
        	        parent.addClass("on").find('input.radioclass').attr("checked", true);
        	    }
			},
			//保存答案
			saveAnswer(){
				var _self = this;
				_self.initialize();
				//校验必填字段
				if(!_self.verifying()){
					return false;
				}
				//定义数组集合，用于往后台传输数据
				var array = new Array();
				//验证选择“其他”选项后是否填写了文本答案
				var flag = false;
				//从最顶级获取全部li
				$(".qs-list").each(function() {
					var obj = $(this);
					var html = _self.getQuestion(obj);
					if(!html){
						flag = true;
					}else{
						//将单个问题内容组装成josn,并存入数组
						array.push(html);
					}
				});
				if(flag){
					layer.msg("请填写“其他”选项的文本答案",{
						area: '200px;',
						offset: '50%'
					});
					return false;
				}
				var params = {
					"projectQuestionnaireId": _self.$route.params.id,
					"customerName": _self.customer.customerName,
					"customerPhone": _self.customer.customerPhone,
					"projectId": _self.project.id,
					"arrayJson": JSON.stringify(array)
				};
				_self.showBtn = false;
				var index = layer.load(0, {shade: false});
				var url = _self.utilHelper.apiUrl + "/customer/projectQuestion/addAnswerByH5";
				_self.$http.post(url, params).then((response)=>{
					layer.close(index);
					var body = response.body;
					console.log(body);
					if(body.res == "1"){
						layer.alert("问卷保存成功");
					}else{
						_self.showBtn = true;
						layer.msg(body.resMsg);
					}
				}, (response) => {
					_self.showBtn = true;
					layer.msg("问卷保存失败");
					console.log(response);
				});
			},
			//组装要提交的数据
			getQuestion(obj){
				var flag = false;
				//获取当前是否必填
				var isRequired = obj.attr("isRequired");
				//获取当前问题的ID
				var questionId = obj.attr("questionId");
				//获取当前问题的类型
				var answerType = obj.attr("answerType");
				//获答案ID、答案文本、"其他答案"ID
				var answerId = "",  answerText = "", select_other = "";
				if(answerType == "1"){
					//获取单选框
					answerId = $('input:radio[name="radioAnswer_'+questionId+'"]:checked').val();
					if(answerId == undefined){
						answerId = "";
					}
					//当选择答案为“其他”时，获取填写的文本答案
					if($('input:radio[name="radioAnswer_'+questionId+'"]:checked').attr("at") == "select_other"){
						select_other = answerId;
						answerText = $("#input_"+questionId).val();
						//判断必答题选择"其他"选项是是否填写了答案
						if(answerText == ""){
							$("#h4_"+questionId).attr("style", "color:red");
							flag = true;
						}
					}
				}else if(answerType == "2"){
					//获取复选框
					$("input[name='checkAnswer_"+questionId+"']").each(function(){
						if($(this).is(':checked')){
					    	answerId += '"' + $(this).attr("value") + '",';	
					    	//当选择答案为“其他”时，获取填写的文本答案
							if($(this).attr("at") == "select_other"){
								select_other = $(this).attr("value");
								answerText = $("#input_"+questionId).val();
								//判断必答题选择"其他"选项是是否填写了答案
								if(answerText == ""){
									$("#h4_"+questionId).attr("style", "color:red");
									flag = true;
								}
							}
					   	}
					});
					//将答案集合组装成数组格式
					if(answerId){
						answerId =  '[' + answerId.substring(0, answerId.length-1) + ']';
					}
				}else if(answerType == "3"){
					//获取文本答案
					answerText = $("#input_"+questionId).val();
				}
			    if(flag){
			    	return false;
			    }
			    //组装json
			    var json = {
			    	"questionId": questionId,
			    	"answerType": answerType,
			    	"answerId": answerId,
			    	"select_other": select_other,
			    	"answerText": answerText
			    };
			    return json;
			},
			//初始化题目颜色
			initialize(){
				$("h4").each(function(){
					$(this).attr("style", "");
				});
			},
			//校验必填字段
			verifying(){
				if(this.customer.customerName == ''){
					layer.tips("请填写您的姓名", "#name",{
						tips: [3, '#FCA639']
					});
					return false;
				}
				if(this.customer.customerPhone == ''){
					layer.tips("请填写您的手机号", "#phone",{
						tips: [3, '#FCA639']
					});
					return false;
				}
				var regExp = /^((13[0-9])|(15[0-9])|(17[0-9])|(18[0-9])|(19[0-9])|(145)|(147)|(149)|(166))+\d{8}$/;  
				if(!regExp.test(this.customer.customerPhone)){
					layer.tips("您填写的手机号码不正确", "#phone",{
						tips: [3, '#FCA639']
					});
					return false;
				}
				return true;
			},
			//重置
			resetAnswer(){
				$(":input").not(":button, :submit, :reset, :hidden").parent().removeClass("on");
				$(":input").not(":button, :submit, :reset, :hidden, :radio").val("");
				$(":input").not(":button, :submit, :reset, :hidden, :text").removeAttr("checked");
			}
		}
	};
</script>

<style type="text/css">
	@import'../../assets/css/questionnaire.css'
</style>